package sg.edu.nus.iss.ooad.jass.ui;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import sg.edu.nus.iss.ooad.jass.controller.JobseekerController;
import sg.edu.nus.iss.ooad.jass.controller.MainController;
import sg.edu.nus.iss.ooad.jass.controller.ResponseController;
import sg.edu.nus.iss.ooad.jass.entity.JobAdvertisement;
import sg.edu.nus.iss.ooad.jass.entity.Jobseeker;
import sg.edu.nus.iss.ooad.jass.entity.Response;
import sg.edu.nus.iss.ooad.jass.ui.widget.AbstractJASSRegularWindow;
import sg.edu.nus.iss.ooad.jass.ui.widget.JASSRegularPanel;

/**
 *
 * This is  List Response Form. This form is to keep track the list of the responses for each job adverisement.
 *
 * @author Isak Rabin (HT082193M)
 * @version 1.0
 * @since 1.0 
 *
 */
public class AdvertiserListResponseForm extends AbstractJASSRegularWindow {

        private static final long serialVersionUID = -5249964030937657737L;
        private static final Logger logger = Logger.getLogger(AdvertiserListResponseForm.class.getName());
        private Panel titlePanel = null;
        private Panel descriptionPanel = null;
        private Button interviewedButton = null;
        private Button rejectedButton = null;
        private Button acceptedButton = null;
        private Button exitButton = null;
        private Panel buttonPanel = null;
        private ArrayList<Response> selectedItem = new ArrayList<Response>();
        private AbstractJASSRegularWindow parent;

        
       /**
        * Constructor of the AdvertiserListResponseForm class.
        * @param parent
        * @param job
        */
        public AdvertiserListResponseForm(AbstractJASSRegularWindow parent, JobAdvertisement job) {
                super("Job Advertisement and Search System", new Dimension(550, 400));
                this.parent = parent;
                setResizable(false);
                initComponents(job);


        }

        /**
         * Initialize Form Components
         * @param job
         */
        public void initComponents(JobAdvertisement job) {
                buttonPanel = new Panel();
                titlePanel = new JASSRegularPanel("Job Advertisment - List of Responses");

                interviewedButton = new Button("Interviewed");
                rejectedButton = new Button("Rejected");
                acceptedButton = new Button("Accepted");

                //set Layout
                buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
                buttonPanel.add(interviewedButton);
                interviewedButton.addActionListener(new interviewedActionListener());

                buttonPanel.add(rejectedButton);
                rejectedButton.addActionListener(new rejectedActionListener());


                buttonPanel.add(acceptedButton);
                acceptedButton.addActionListener(new acceptedActionListener());

                exitButton = new Button("Exit");
                buttonPanel.add(exitButton);
                exitButton.addActionListener(new exitActionListener());
                setLayout(new BorderLayout(5, 5));
                add(titlePanel, BorderLayout.NORTH);
                display(job);
                add(buttonPanel, BorderLayout.SOUTH);


        }

        /**
         * Display the responses for each job advertisement.
         * @param job
         */
        public void display(JobAdvertisement job) {
                ResponseController responseController = new ResponseController();
                JobseekerController jobseekerController = new JobseekerController();
                try {

                        ArrayList<Response> responses = (ArrayList<Response>) responseController.findResponseByJobAdvertisementID(job.getID());
                        if (responses.size() > 0) {
                                descriptionPanel = new Panel();

                                int i = 0;
                                for (Response response : responses) {
                                        Jobseeker jobseeker = jobseekerController.retrieveJobseeker(response.getJobseekerID());
                                        Panel subTitlePanel = new Panel();
                                        Panel subPanel = new Panel();
                                        Label responseLabel = new Label("Click here to view profile");
                                        responseLabel.setForeground(Color.RED);
                                        Checkbox c = new Checkbox("Response [" + (i++) + "]");
                                        responseLabel.addMouseListener(new ViewProfileActionListener(jobseeker , this));
                                        c.addItemListener(new responseItemListener(response));
                                        subTitlePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
                                        subTitlePanel.setPreferredSize(new Dimension(550, 30));
                                        subTitlePanel.add(c);
                                        subTitlePanel.add(responseLabel);

                                        subPanel.setLayout(new GridLayout(4, 2, 5, 5));
                                        subPanel.add(new Label("Job Title :"));
                                        subPanel.add(new Label(job.getJobTitle()));
                                        subPanel.add(new Label("Job Seeker :"));
                                        subPanel.add(new Label(jobseeker.getName()));
                                        subPanel.add(new Label("Response Date :"));
                                        subPanel.add(new Label(response.getResponseDate()));
                                        subPanel.add(new Label("Response Status: "));
                                        subPanel.add(new Label(transformStatus(response.getResponseStatus())));

                                        descriptionPanel.add(subTitlePanel);
                                        descriptionPanel.add(subPanel);
                                }
                                add(descriptionPanel, BorderLayout.CENTER);

                        }

                } catch (Exception ex) {
                        logger.log(Level.SEVERE, null, ex);
                }

        }

        /**
         * To reset form.
         */
        @Override
        public void resetForm() {
                throw new UnsupportedOperationException("Not supported yet.");
        }

        /**
         * Response Item listener to handle the action when  check box item has been checked.
         */
        class responseItemListener implements ItemListener {

                private Response item;

                public responseItemListener(Response item) {
                        this.item = item;
                }

                public void itemStateChanged(ItemEvent ie) {
                        if (ie.getStateChange() == ItemEvent.SELECTED) {
                                selectedItem.add(item);
                        } else if (ie.getStateChange() == ItemEvent.DESELECTED) {
                                selectedItem.remove(item);
                        }

                }
        }

        /**
         * Interviewed Action Listener to handle the action when 'interview' button has been pressed.
         */
        class interviewedActionListener implements ActionListener {

                public void actionPerformed(ActionEvent evt) {
                        if (!selectedItem.isEmpty()) {
                                boolean success = updateResponseStatus(selectedItem, "I");
                                if (success) {
                                        displayMessage("Job Response Info","Update Successfully");
                                        close(); 
                                } else {
                                        displayMessage("Job Response Info","Failed to update");
                                }
                        } else {
                                displayMessage("Job Response Info","Please at lease choose one job seeker to interview");
                        }

                }
        }

        /**
         * View profile Action Listener to handle the action when 'View Profile' button has been pressed.
         */
        class ViewProfileActionListener implements MouseListener {

                private Jobseeker item;
                private AbstractJASSRegularWindow parent;

                public ViewProfileActionListener(Jobseeker item , AbstractJASSRegularWindow parent) {
                        this.item = item;
                        this.parent=parent;
                }
                

                public void mouseClicked(MouseEvent e) {
                        MainController controller = MainController.getInstance();
                        controller.setJobSeeker(item); 
                        controller.gotoScreen(MainController.JASS_JOB_SEEKER_PROFILE_FORM, parent);
                }

                public void mousePressed(MouseEvent e) {
                }

                public void mouseReleased(MouseEvent e) {
                }

                public void mouseEntered(MouseEvent e) {
                }

                public void mouseExited(MouseEvent e) {
                }
        }

       /**
         * Accepted Action Listener to handle the action when 'accept' button has been pressed.
         */
        class acceptedActionListener implements ActionListener {

                public void actionPerformed(ActionEvent evt) {
                        if (!selectedItem.isEmpty()) {
                                boolean success = updateResponseStatus(selectedItem, "A");
                                if (success) {
                                       displayMessage("Job Response Info","Update successfully");
                                       close();
                                } else {
                                       displayMessage("Job Response Info","Failed to update");
                                }
                        } else {
                               displayMessage("Job Response Info","Please at lease choose one job seeker  to accept");
                        }
                }
        }

       /**
         * reject Action Listener to handle the action when 'rejected' button has been pressed.
         */
        class rejectedActionListener implements ActionListener {

                public void actionPerformed(ActionEvent evt) {
                        // throw new UnsupportedOperationExcReption("Not supported yet.");
                        if (!selectedItem.isEmpty()) {
                                boolean success = updateResponseStatus(selectedItem, "R");
                                if (success) {
                                        displayMessage("Job Response Info ","Update Successfully");
                                        close();
                                } else {
                                        displayMessage("Job Response Info", "Failed to update");
                                }
                        } else {
                                displayMessage("Job Response Info","Please at lease choose one job seeker to reject");
                        }
                }
        }

       /**
         * Exit Action Listener to handle the action when 'exit' button has been pressed.
         */
        class exitActionListener implements ActionListener {

                public void actionPerformed(ActionEvent e) {
                        close();
                }
        }
        

         /**
         * Update the response status.
         */

        private boolean updateResponseStatus(ArrayList<Response> responses, String status) {
                ResponseController responsecontroller = new ResponseController();
                boolean success = false;
                try {
                        for (Response rp : responses) {
                                rp.setResponseStatus(status);
                                success = responsecontroller.updateResponse(rp);
                        }
                } catch (Exception e) {
                        logger.log(Level.SEVERE, null, e);

                }
                return success;
        }

       
     /**
      * Transform the status.
      * @param status
      * @return
      */
        private String transformStatus(String status) {
                if (status.equals("D")) {
                        return "DRAFT";
                } else if (status.equals("A")) {
                        return "ACCEPTED";
                } else if (status.equals("I")) {
                        return "INTERVIEWED";
                } else if (status.equals("R")) {
                        return "REJECTED";
                } else {
                        return "";
                }
        }


       /**
        * Attach the component to form
        * @param c
        * @param gridx
        * @param gridy
        * @param gridwidth
        * @param gridheight
        * @param fill
        */


        @Override
        public void attachComponent(Component c, int gridx, int gridy, int gridwidth, int gridheight, int fill) {
                throw new UnsupportedOperationException("Not supported yet.");
        }
}
